package com.ethan.springcloud.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author daifei
 * @date 2019/5/7
 */
@Slf4j
@Component
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Object accessToken = request.getParameter("accessToken");
        return !StringUtils.isEmpty(accessToken);
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info("send to：{}， request to-{}", request.getMethod(), request.getRequestURL());
        Object accessToken = request.getParameter("accessToken");
        if (!"GATEWAY".equals(accessToken)) {
            log.warn("accessToken is empty!!!");
            ctx.setSendZuulResponse(false);
            ctx.getResponse().setContentType("text/html;charset=UTF-8");
            ctx.setResponseBody("非法请求token!!!");
            ctx.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
        }
        return null;
    }
}
